﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LotusIslandOrderProcessing.model
{
    /// <summary>
    /// 二维码生成
    /// </summary>
    public class EWMMsg
    {
        private static EWMMsg instance;
        private EWMMsg() { }
        public static EWMMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new EWMMsg();
                }
                return instance;
            }
        }
        #region 二维码通讯
        public bool AllBol = true;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        //private List<byte> buffer = new List<byte>();
        //public static bool IsMsgError = true;
        //string nostrs = "";
        //public Thread All_thr;
        #region 串口方式
        //public void IOSerial_Thr()
        //{
        //    try
        //    {
        //        var ddd = SerialPort.GetPortNames().ToList();
        //        if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.EWMPortName)))
        //        {
        //            Thread.Sleep(1000);
        //            IOSerial_Thr();
        //        }
        //        EWMSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.EWMPortName, 115200, "", 8, 1);//其他串口通讯
        //        EWMSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
        //    }
        //    catch (Exception)
        //    {
        //        EWMSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
        //        Thread.Sleep(100);
        //        IOSerial_Thr();
        //    }
        //}
        //private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    try
        //    {
        //        byte[] result = new byte[EWMSerialPort.Instance.serialPort.BytesToRead];
        //        EWMSerialPort.Instance.serialPort.Read(result, 0, EWMSerialPort.Instance.serialPort.BytesToRead);
        //        buffer.AddRange(result);
        //        string str = "";
        //        if (buffer.Count > 0x03)
        //            str += $"{Encoding.ASCII.GetString(result)}";
        //        MsgShow(str);
        //        Thread.Sleep(1);
        //    }
        //    catch (Exception)
        //    {
        //        return;
        //    }
        //}
        #endregion
        #region usb方式
        // public bool AllBol = true;
        public static Thread DecodeThread = null;
        delegate void ShowRichTextBoxMsgRef(string lpMsg);
        //循环是否启动标记
        public static bool bIsLoop = false;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        Vbarapi Api = new Vbarapi();
        public void IOSerial_Thr()
        {
            try
            {
                if (Api.openDevice())
                {
                    StartDecodeThread();
                }
                else
                {
                    Thread.Sleep(100);
                    IOSerial_Thr();
                }
            }
            catch (Exception)
            {
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        /// <summary>
        /// 方法：开始解码线程方法
        /// </summary>
        private void StartDecodeThread()
        {
            bIsLoop = true;
            DecodeThread = new Thread(new ThreadStart(DecodeThreadMethod));
            DecodeThread.IsBackground = true;
            DecodeThread.Start();
        }

        /// <summary>
        /// 方法：停止解码线程方法
        /// </summary>
        private void StopDecodeThread()
        {
            bIsLoop = false;
            if (DecodeThread != null)
            {
                DecodeThread.Abort();
                while (DecodeThread.ThreadState != ThreadState.Aborted)
                {
                    Thread.Sleep(50);
                }
            }
        }
        public string Decoder()
        {
            byte[] result;
            string sResult = null;
            int size;
            if (Api.getResultStr(out result, out size))
            {

                string msg = System.Text.Encoding.Default.GetString(result);
                byte[] buffer = Encoding.UTF8.GetBytes(msg);
                sResult = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            }
            else
            {
                sResult = null;
            }
            return sResult;
        }

        /// <summary>
        /// 方法：扫码线程方法
        /// </summary>
        private void DecodeThreadMethod()
        {
            string decoderesult = null;
            //  ShowRichTextBoxMsgRef ShowRichTextBoxMsgRef_Instance = new ShowRichTextBoxMsgRef(ShowRichTextBoxMsg);
            do
            {
                //+ Environment.NewLine
                decoderesult = Decoder();
                if (decoderesult != null)
                {
                    MsgShow(decoderesult);
                    decoderesult = null;
                }
            }
            while (bIsLoop);
        }
        /// <summary>
        /// 方法：显示文本信息
        /// </summary>
        /// <param name="lpRichTextBox"></param>
        /// <param name="lpMsg"></param>
        //private void ShowRichTextBoxMsg(string lpMsg)
        //{
        //   // lpRichTextBox.AppendText(lpMsg);
        //}
        #endregion
        public string ewm = "";
        public void MsgShow(string str)
        {
            try
            {
                if (str.Length > 0)
                {
                    ewm += str;
                    var msgs = ewm.Split('*');
                    if (msgs.Count() >= 4)
                    {
                        if (nostrs.Length < 18)
                        {
                            str = nostrs + msgs[3];
                            nostrs = "";
                        }
                        else
                            str = msgs[0];
                        var msg = str.Split('#');
                        if (msg.Count() > 1)
                        {
                            if (msg[1].Length >= 1)
                            {
                                if (msg[1].Substring(0, 1) == "2")
                                {
                                    EWM eWM = new EWM();
                                    eWM.orderNum = msg[0];
                                    eWM.deviceId = msg[1].Substring(0, 1);
                                    string list = JsonConvert.SerializeObject(eWM);
                                    var data = HttpMsg.Instance.orderQueueMsg(list);
                                    //var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                                    if (data != null)
                                    {
                                        var listdata = JsonConvert.DeserializeObject<HTTPMsg>(data);
                                        if (listdata != null)
                                        {
                                            switch (listdata.code)
                                            {
                                                case "0":
                                                    var data1 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.SMCG);
                                                    Api.Channel_show(data1);
                                                    break;
                                                case "1":
                                                    var data2 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.ZZZ);
                                                    Api.Channel_show(data2);
                                                    break;
                                                case "2":
                                                    var data3 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.SMSB);
                                                    Api.Channel_show(data3);
                                                    break;
                                                case "3":
                                                    var data4 = EWMSerialPort.Instance.SerialSend(EwmModel.Instance.CMYSY);
                                                    Api.Channel_show(data4);
                                                    break;
                                            }
                                        }
                                    }
                                    /// SpeechVoice.Instance.VoicePlayback(listdata.msg);
                                    ewm = "";
                                }
                                else
                                {
                                    SpeechVoice.Instance.VoicePlayback("Please go to Machine No. " + msg[1].Substring(0, 1) + "to scan the QR code to make your coffee");
                                    ewm = "";
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    else if (msgs.Count() == 1)
                    {
                        // ewm +=str;
                    }
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public class EWM
        {
            public string orderNum { get; set; }
            public string deviceId { get; set; } = "2";
            public int type { get; set; } = 0;//0摩通 1 国贸
        }
        #endregion
    }
}
